<template>
  <div class="search-tools">
    <ul class="search-list">
      <li>
        <label class="label">学年：</label
        ><a-select
          :value="search.schoolYear"
          placeholder="全部"
          @change="changeSchoolYear"
        >
          <a-select-option
            v-for="item in list.schoolYear"
            :key="item.id"
            :value="item.id"
            >{{ item.time }}</a-select-option
          >
        </a-select>
      </li>
      <li>
        <label class="label">年级学科：</label>
        <a-cascader
          :allowClear="false"
          :value="search.gradeAndSubject"
          :options="list.grade"
          placeholder="全部"
          @change="changeGrade"
        ></a-cascader>
      </li>
      <li v-if="props.active !== 'grade'">
        <label class="label">班级：</label
        ><a-select
          :value="search.class"
          placeholder="全部"
          @change="changeClass"
        >
          <a-select-option
            v-for="item in list.class"
            :key="item.id"
            :value="item.id"
            >{{ item.class_name }}</a-select-option
          >
        </a-select>
      </li>
      <li class="date">
        <label class="label">时间：</label>
        <span
          class="date-item"
          :class="{ active: activeDate === DateEnum.WEEK }"
          @click="changeTimeOption(DateEnum.WEEK)"
          >近一周</span
        >
        <span
          class="date-item"
          :class="{ active: activeDate === DateEnum.MONTH }"
          @click="changeTimeOption(DateEnum.MONTH)"
          >近一月</span
        >
        <span
          class="date-item"
          :class="{ active: activeDate === DateEnum.THREE_MONTH }"
          @click="changeTimeOption(DateEnum.THREE_MONTH)"
          >近三月</span
        >
        <span
          class="date-item"
          :class="{ active: activeDate === DateEnum.HALF_YEAR }"
          @click="changeTimeOption(DateEnum.HALF_YEAR)"
          >近半年</span
        >
        <a-range-picker
          @change="changeDate"
          format="YYYY/MM/DD"
          :value="search.date"
          separator="至"
          :placeholder="['开始日期', '结束日期']"
        >
        </a-range-picker>
      </li>
    </ul>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { getSchoolYear } from '@/apis/situation-report/index'
import { useAuthStore } from '@/stores/auth-store.js'
import { useSituationReport } from '@/stores/situation-report'
import { onMounted, computed } from 'vue'
// import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import _ from 'lodash'
dayjs.locale('en')
const { setSearch } = useSituationReport()
const userStore = useAuthStore()
const { getUserInfoFun } = useAuthStore()
const DateEnum = {
  WEEK: 'week',
  MONTH: 'month',
  THREE_MONTH: 'three-month',
  HALF_YEAR: 'half-year'
}

const props = defineProps({
  active: {
    type: String,
    default: 'grade'
  }
})
const list = reactive({
  schoolYear: [],
  grade: [],
  class: [],
  originList: []
})
const activeDate = ref(DateEnum.THREE_MONTH)
const search = reactive({
  schoolYear: '',
  gradeAndSubject: [],
  date: [
    dayjs(dayjs().subtract(3, 'month'), 'YYYY-MM-DD'),
    dayjs(dayjs(), 'YYYY-MM-DD')
  ],
  class: ''
})

const getParams = computed(() => {
  const res = {
    school_id: userStore.userInfo.school_id,
    grade_id: search.gradeAndSubject[0],
    subject_id: search.gradeAndSubject[1],
    start_time: dayjs(search.date[0]).startOf('day').unix(),
    end_time: dayjs(search.date[1]).endOf('day').unix(),
    class_id: search.class
  }
  return res
})

const changeTimeOption = type => {
  activeDate.value = type
  changeSelectedDate(type)
}

const changeSelectedDate = val => {
  switch (val) {
    case DateEnum.WEEK:
      search.date[0] = dayjs(dayjs().subtract(7, 'day'), 'YYYY-MM-DD')
      break
    case DateEnum.MONTH:
      search.date[0] = dayjs(dayjs().subtract(1, 'month'), 'YYYY-MM-DD')
      break
    case DateEnum.THREE_MONTH:
      search.date[0] = dayjs(dayjs().subtract(3, 'month'), 'YYYY-MM-DD')
      break
    case DateEnum.HALF_YEAR:
      search.date[0] = dayjs(dayjs().subtract(6, 'month'), 'YYYY-MM-DD')
      break
  }
  search.date[1] = dayjs(dayjs(), 'YYYY-MM-DD')
  setSearch(getParams.value)
}

const changeDate = item => {
  search.date[0] = item?.[0]
  search.date[1] = item?.[1]
  setSearch(getParams.value)
}

const getSchoolYearList = async () => {
  const params = { school_id: userStore.userInfo?.school_id }
  const { data } = await getSchoolYear(params)
  list.schoolYear = data || []
  search.schoolYear = list.schoolYear[0].id
}

const changeSchoolYear = val => {
  search.schoolYear = val
  const index = list.schoolYear.findIndex(item => item.id === val)
  if (index > -1) {
    const time = list.schoolYear[index]?.time
    const start = time.split('-')[0]
    search.date[0] = dayjs(`${parseFloat(start)}-09-01`, 'YYYY-MM-DD')
    search.date[1] = dayjs(`${parseFloat(start) + 1}-08-31`, 'YYYY-MM-DD')
  }
  setSearch(getParams.value)
}

const changeClass = val => {
  search.class = val
  setSearch(getParams.value)
}

const changeGrade = val => {
  search.gradeAndSubject = val
  handleClassList()
  search.class = list.class[0]?.id
  setSearch(getParams.value)
}

const handleList = () => {
  list.grade = []
  for (
    let gradeIndex = 0;
    gradeIndex < userStore.allGradeList.length;
    gradeIndex++
  ) {
    let subjectList = []
    // 过滤出当前年级下的所有科目
    const gradeGroup = userStore.flattenGscList.filter(item => {
      return item.grade_num === userStore.allGradeList[gradeIndex].value
    })
    subjectList = _.uniqBy(gradeGroup, 'subject_num')
    const tempList = subjectList
      .filter(item => item.subject_num !== -1)
      .sort((item1, item2) => item1.subject_num - item2.subject_num)
    list.grade?.push({
      ...userStore.allGradeList[gradeIndex],
      children: tempList.map(subject => {
        return {
          label: subject.subject_name,
          value: subject.subject_num,
          ...subject
        }
      })
    })
  }
}

const handleClassList = () => {
  const classList =
    userStore.flattenGscList.filter(
      item =>
        parseFloat(item.subject_num) === search.gradeAndSubject[1] &&
        item.grade_num === search.gradeAndSubject[0]
    ) || []
  list.class = _.uniqBy(classList, 'id')
}

const initData = async () => {
  await getSchoolYearList()
  await handleList()
  search.gradeAndSubject = [
    list.grade[0].value,
    list.grade[0].children?.[0]?.value
  ]
  handleClassList()
  search.class = list.class[0]?.id
  setSearch(getParams.value)
}

onMounted(async () => {
  await getUserInfoFun()
  initData()
})

defineExpose({
  changeClass
})
</script>
<style lang="less" scoped>
@import '../style.less';

.search-tools {
  border-radius: @big-radius;
  padding: @gap;
  background: #fff;

  .search-list {
    display: flex;
    align-items: center;
    justify-content: space-between;

    li {
      list-style-type: none;
      display: flex;
      align-items: center;
      gap: 6px;
    }

    .label {
      font-weight: 500;
    }

    .date {
      &-item {
        cursor: pointer;
        display: inline-block;
        padding: 4px 8px;
        color: @minor-font-color;
        border: 1px #fff solid;
        border-radius: 6px;

        &.active {
          border: 1px solid #4d88ff;
          color: #4d88ff;
          background: rgb(77 136 255 / 0.15);
        }
      }
    }

    :deep(.ant-select) {
      max-width: 166px;
      min-width: 150px;
      height: fit-content;

      .ant-select-selector {
        border-radius: @small-radius;
      }
    }

    :deep(.ant-picker) {
      padding: 6px 8px;

      input {
        text-align: center;

        &:focus {
          border: none;
        }
      }

      border-radius: @small-radius;

      .ant-picker-focused {
        border: none;
      }
    }
  }
}
</style>
